package com.ala4.oxcafe.boot;

import com.ala4.oxcafe.boot.async.ExportAsyncTemplate;
import com.ala4.oxcafe.boot.repository.ExportTaskDTO;
import com.ala4.oxcafe.common.utils.date.DateUtil;
import com.ala4.oxcafe.enums.AsyncTaskStateEnum;
import com.ala4.oxcafe.properties.FileProperties;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;

/**
 * 把文件导出到本地文件夹
 *
 * @author PING
 * @version 1.0.0
 * @date 2025/8/1 17:58
 */
@Service
@AllArgsConstructor
public class LocalFileExportTemplate extends ExportAsyncTemplate {

    private final FileProperties fileProperties;

    @Override
    public Object doWhenFinish(ExportTaskDTO dto, Path tempFile) throws IOException {

        Path targetDir = Paths.get(fileProperties.getUploadFolder() + DateUtil.nowDateString("yy/MM-dd"));

        // 确保目标目录存在
        if (!Files.exists(targetDir)) {
            Files.createDirectories(targetDir);
        }

        // 构建目标文件路径
        String fileName = dto.getTaskName() + System.currentTimeMillis() + ".xlsx";
        Path targetFile = targetDir.resolve(fileName);

        // 直接移动临时文件到目标位置（高效操作）
        Files.move(tempFile, targetFile, StandardCopyOption.REPLACE_EXISTING);

        // 回写状态
        dto.setDownloadUrl(targetFile.toUri().toString());
        dto.setState(AsyncTaskStateEnum.DONE);
        dto.setEndDateTime(LocalDateTime.now());
        exportTaskRepository.update(dto);

        return targetFile.toAbsolutePath().toString();
    }

    @Override
    public Object doWhenOccurException(ExportTaskDTO dto, Throwable e) {
        dto.setState(AsyncTaskStateEnum.ERROR);
        dto.setEndDateTime(LocalDateTime.now());
        dto.setErrorInfo(e.getMessage());
        exportTaskRepository.update(dto);
        return null;
    }
}
